<?php
namespace app\index\controller;

use think\Db;
use think\Controller;


//header("Access-Control-Allow-Origin:http://152.136.128.96"); // 允许指定域访问跨域资源
//header("Access-Control-Allow-Origin:http://sparkdesignbox.cn"); // 允许指定域访问跨域资源
header("Access-Control-Allow-Credentials:true");
header("Set-Cookie: hidden=value; httpOnly");//预防XSS攻击

class Index extends Controller
{

    /**启动broadcast server，画布协同编辑时使用
     *
     * @return mixed 主页HTML
     */
    public function index()
    {
        //curl：相当于异步启动广播server，防止server启动时的监听代码造成阻塞（得再刷新一次才能执行启动server之后的代码）
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "http://152.136.128.96/index/Startbroadcastserver");
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_exec($ch);
        //dump(curl_error($ch));

        curl_close($ch);

        /*$path = "../broadcastServer/server.js";
        exec("node ".$path." 2>&1");*/


        if(isset($_COOKIE['user']))
            return $this->getProjects($_COOKIE['user']);
        else {
            return $this->fetch('homePage');
        }
    }

    public function getHomePage(){
        return $this->fetch('homePage');
    }

    /**
     * @return mixed 登录页面
     */
    public function login()
    {
        return $this->fetch('login');
    }

    /**检查用户名和密码是否正确
     *
     * @return mixed|void 登录成功-项目页；登录失败-失败页，自动跳转到登录页
     */
    public function checkLogin()
    {
        $post = json_decode(file_get_contents("php://input"),true);

        if(isset($_POST['name']) && isset($_POST['psw'])) {

        // if(($POST['name']=='s') && ($POST['psw']=='s')) {

            //echo $_POST['encrypsw'];
            if(isset($_POST['isNiepan']) && $_POST['isNiepan'] == 'Y'){

                $tokendata['stuNo']=$_POST['name'];
                $tokendata['password']=$_POST['encrypsw'];


                $tokenjson=json_encode($tokendata);
                $httpurl="https://www.ourspark.org/api/loginUserPass";
                $reqstr=$this->http_request($httpurl,$tokenjson);
                $reqstr=json_decode($reqstr);

                //var_dump($reqstr);

                if($reqstr->state == true){
                    $userInfo = json_decode($reqstr->user);
                    $username = $userInfo->username;
                    $stuNo = $userInfo->stuNo;
                    $school = $userInfo->school;
                    $realName = $userInfo->realName;

                    $fakePassword = md5(explode('-',$userInfo->UUID)[0]);

                    $list = Db::table('sheji.users')
                        ->field('id')
                        ->where(['stuNo' => $stuNo])
                        ->find();

                    if(sizeof($list) == 0) {
                        Db::table('sheji.users')
                            ->data(['usr_name' => $username, 'password' => $fakePassword, 'stuNo' => $stuNo, 'school' => $school, 'realName' => $realName])
                            ->insert();

                        $getLastId = Db::name('sheji.users')->getLastInsID();
                    }else{
                        $getLastId = $list['id'];
                    }


                    cookie('user', $getLastId, 18000);
                    cookie('username', $username, 18000);

                    $this->addUserHistory($_COOKIE['user'], "login", 0, 0, 0);

                    return $this->getProjects($_COOKIE['user']);

                }else{
                    return $this->error('登录失败！请检查用户名及密码。', url('index/login'));

                }
            }




                $list = Db::table('sheji.users')
                    ->field('id,usr_name')
                    ->where(['usr_name' => $_POST['name'],
                        'password' => $_POST['psw']])
                    ->find();


                if (sizeof($list) == 0) {
                    return $this->error('登录失败！请检查用户名及密码。', url('index/login'));
                } else {
                    //setcookie("user", $list['id'], time()+3600);
                    //setcookie("username", $list['usr_name'], time()+3600);

                    cookie('user', $list['id'], 18000);
                    cookie('username', $list['usr_name'], 18000);

                    $this->addUserHistory($_COOKIE['user'], "login", 0, 0, 0);
                    //return $this->fetch('homePage');
                    return $this->getProjects($_COOKIE['user']);
                    //return $this->success('登录成功！',url('index/index'));
                }

        }else{
            if(isset($_COOKIE['user'])) {
                return $this->getProjects($_COOKIE['user']);
            }else{
                return $this->fetch('homePage');
            }
        }

    }


    function http_request($url,$data){
        $curl=curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type:application/json;charset=utf-8'));

        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
        $output=curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**清除user和username COOKIE
     * @return mixed 主页
     */
    public function logout(){
        //setcookie("user", "", time()-1);
        //setcookie("username", "", time()-1);
        $this->addUserHistory($_COOKIE['user'],"logout",0,0,0);


        cookie('user',null);
        cookie('username',null);


        return $this->fetch('homePage');
        //return $this->success('登出成功！',"index/index");
    }

    /**
     * @return mixed 注册页面
     */
    public function register(){
        return $this->fetch('register');
    }

    /**检查用户名是否被占用
     *
     * @return mixed|void 注册成功-项目页；注册失败-失败页自动跳回
     */
    public function checkRegister(){
        $list = Db::table('sheji.users')
            ->field('id')
            ->where(['usr_name'=> $_POST['username']])
            ->find();

        if(sizeof($list) == 0){
            return true;
        }else{
            //return $this->error('注册失败！用户名已被占用。',url('index/register'));
            return false;
        }
    }


    public function afterRegister(){

        if($this->checkRegister()){
            Db::table('sheji.users')
                ->data(['usr_name' => $_POST['username'], 'password' => $_POST['password1'], 'stuNo'=>$_POST['stuNo'],'email' => $_POST['email']])
                ->insert();
        }


        $list2 = Db::table('sheji.users')
            ->field('id,usr_name')
            ->where(['usr_name'=> $_POST['username']])
            ->find();

        //setcookie("user", $list2['id'], time()+3600);
        //setcookie("username", $list2['usr_name'], time()+3600);

        cookie('user',$list2['id'], 18000);
        cookie('username',$list2['usr_name'], 18000);


        $this->addUserHistory($_COOKIE['user'],"register",0,0,0);

        //return $this->fetch('homePage');
        return $this->getProjects($_COOKIE['user']);
        //return $this->success('注册成功！',url('index/index'));
    }

    /**获取该用户加入的项目id及名称
     *
     * @param $userId 用来检查当前COOKIE是否和URL中的userId一致
     * @return mixed 项目页面
     */
    public function getProjects($userId){
        //$userId = $_GET['userId'];
        if(isset($_COOKIE['user']) && $userId == $_COOKIE['user']) {
            $list = Db::table('sheji.user_prj_links')
                ->alias('t1')
                ->join('sheji.projects t2', 't1.prj_id = t2.id')
                ->field('prj_id,prj_name,date')
                ->where('user_id', $userId)
                ->where('confirmed','Y')
                ->select();

            //dump($list);

            //添加项目成员数 属性
            for($i = 0; $i < sizeof($list); $i++){
                $list[$i]['members_size'] = sizeof($this->getPrjMembers($list[$i]['prj_id']));

            }

            $this->assign("projects", $list);


            return $this->fetch('projects');
        }
    }

    /**添加项目功能
     *
     * @param $userId
     */
    public function addProject($userId){

        $name = $_POST['name'];
         Db::table('sheji.projects')
             ->data(['prj_name'=>$name, 'creator_id'=>$userId, 'date'=>date('Y-m-d H:i:s',time())])
             ->insert();

        $getLastId = Db::name('sheji.projects')->getLastInsID();
        /*
        $getLastId = Db::table('sheji.projects')
            ->field('id')
            ->where('prj_name', $name)
            ->find();*/

         //add to user_prj_links
        Db::table('sheji.user_prj_links')
            ->data(['prj_id'=>$getLastId, 'user_id'=>$userId,'confirmed'=>'Y'])
            ->insert();

        //add default tools(one per tool-type) to this project
        $tool_type_arr = ['共感图','HMW'];
        foreach ($tool_type_arr as $item) {
            Db::table('sheji.tools')
                ->data(['prj_id' => $getLastId, 'tool_type' => $item, 'extra' => ''])
                ->insert();
        }

        Db::table('sheji.tools')
            ->data(['prj_id' => $getLastId, 'tool_type' => '四象限法', 'extra' => 'purpose-;type-可行性——价值'])
            ->insert();




         //return $this->fetch('projects');
    }

    /**更改项目名称
     *
     * @param $prjId
     * @param $prjName 新的名称
     * @return mixed 该项目的工具页面
     */
    public function changePrjName($prjId,$prjName){

        Db::table('sheji.projects')
            ->where('id', $prjId)
            ->update(['prj_name' => $prjName]);

        return $this->getTools($prjId);
    }

    /**添加项目成员
     *
     */
    public function addPrjMember(){
        $userId = $_POST['userId'];
        $prjId = $_POST['prjId'];

        //如果输入用户名添加
        if( ! is_numeric($userId)) {
            $list = Db::table('sheji.users')
                ->field('id')
                ->where('usr_name', $userId)
                ->find();
            $userId = $list['id'];
        }


        //重新判断一下有没有重复，防止提交表单后刷新浏览器重复添加
       if($this->isUserAlreadyIn() == "1") {
           Db::table('sheji.user_prj_links')
               ->data(['prj_id' => $prjId, 'user_id' => $userId, 'confirmed'=> 'N', 'invited_by'=>$_COOKIE['user']])
               ->insert();
       }else if($this->isUserAlreadyIn() == "2"){
           Db::table('sheji.user_prj_links')
               ->where(['prj_id' => $prjId, 'user_id' => $userId])
               ->update(['confirmed' => 'N']);
       }

        //return $this->getTools($prjId);
    }

    /**删除项目成员
     *
     * @return mixed 该项目的工具页面
     */
    public function delPrjMember(){
        $userId = $_POST['userId'];
        $prjId = $_POST['prjId'];

        Db::table('sheji.user_prj_links')
            ->where(['prj_id' => $prjId, 'user_id' => $userId])
            ->delete();

        return $this->getTools($prjId);
    }

    /**用户是否存在于数据库
     *
     * @return string "0"-不存在；"1"-存在
     */
    public function isUserIdExist(){
        $userId = $_POST['userId'];


        if( ! is_numeric($userId)) {
            $list = Db::table('sheji.users')
                ->field('id')
                ->where('usr_name', $userId)
                ->find();
            $userId = $list['id'];
        }

        $list = Db::table('sheji.users')
            ->field('usr_name')
            ->where('id', $userId)
            ->find();

        if(sizeof($list) == 0){
            return "0";
        }else
            return "1";
    }

    /**用户是否已经存在于该项目中
     *
     * @return string "0"-状态为确认加入或已被邀请；"2"-已拒绝邀请；"1"-其他
     */
    public function isUserAlreadyIn(){
        $userId = $_POST['userId'];
        $prjId = $_POST['prjId'];


        if( ! is_numeric($userId)) {
            $list = Db::table('sheji.users')
                ->field('id')
                ->where('usr_name', $userId)
                ->find();
            $userId = $list['id'];
        }

        //判断是否曾经被拒绝加入
        $list = Db::table('sheji.user_prj_links')
            ->field('id')
            ->where(['prj_id'=> $prjId, 'user_id' => $userId, 'confirmed'=>'R'])
            ->find();

        if(sizeof($list) != 0){
            return "2";
        }


        //判断是否已经确认加入或已经被发送邀请
        $list = Db::table('sheji.user_prj_links')
            ->field('id')
            ->where(['prj_id'=> $prjId, 'user_id' => $userId])
            ->find();
        if(sizeof($list) != 0){
            return "0";//之前已经在项目中了
        }else
            return "1";
    }

    public function getQuesBank(){
        $list = Db::table('sheji.question_bank')
            ->where('id','<=',2)
            ->select();

        $this->assign('quesBank',$list);
    }


    public function getSingleQuesBank(){
        if(!isset($_COOKIE['user'])){
            return $this->fetch('homePage');
        }
        $list = Db::table('sheji.question_bank')
            ->where('id','>',2)
            ->order('display_order')
            ->select();



        $this->assign('quesBank',$list);
        return $this->fetch('single_question_bank');
    }


    public function getSingleQuesRecords($quesId, $userId){

        $pre_list = Db::table('sheji.ques_prepared_records qu')
            ->leftJoin('sheji.business_canvas_type t','t.id=qu.type_id')
            ->field('qu.*,type_name')
            ->where('ques_id',$quesId)
            ->select();


        $list = Db::table('sheji.ques_records qu')
            ->leftJoin('sheji.business_canvas_type t','t.id=qu.type_id')
            ->leftJoin('sheji.ques_prepared_records pre','qu.prepared_id=pre.id')
            ->field('qu.*,type_name,pre.user_travel_column')
            ->where('qu.ques_id',$quesId)
            ->where('author_id',$userId)
            ->select();


        //存用户旅程地图的“情绪曲线”数据
        $emotion_curve_data = [[0, 0], [1, 0], [2, 0], [3, 0]];
        for($j=0; $j < sizeof($list); $j++){
            if($list[$j]['type_id'] == 43){ // 即“情感波动”
                if(! is_numeric($list[$j]['contents'] )){ //为了和之前写文字内容的区分
                    continue;
                }

                $xAxis = (int)$list[$j]['user_travel_column'] - 1;
                $yAxis = (int)$list[$j]['contents'];
                $emotion_curve_data[$xAxis] = [$xAxis,$yAxis];

                //var_dump(emotion_curve_data);
            }
        }

        $this->assign('emotion_curve_data',$emotion_curve_data);

        //情绪曲线节点的prepared_id数据
        $emotion_curve_prepared_id = [0,0,0,0];
        for($i=0; $i < sizeof($pre_list); $i++){
            if($pre_list[$i]['type_id'] == 43){ // 即“情感波动”
                $xAxis = (int)$pre_list[$i]['user_travel_column'] - 1;// 避免顺序错乱，按user_travel_column排序
                $emotion_curve_prepared_id[$xAxis] = $pre_list[$i]['id'];
            }
        }

        $this->assign('emotion_curve_prepared_id',$emotion_curve_prepared_id);


        // 用学生答题的内容，替代prepared的空内容
        for($i=0; $i < sizeof($pre_list); $i++){
            if(strlen($pre_list[$i]['contents']) == 0){
                for($j=0; $j < sizeof($list); $j++){
                    if($list[$j]['prepared_id'] == $pre_list[$i]['id']){
                        $pre_list[$i]['contents'] = $list[$j]['contents'];
                        //array_splice($list,$j,1);

                    }
                }
            }
        }

        $this->assign('pre_records',$pre_list);
        //$this->assign('records',$list);

        //----------查询records importance flag
        $preparedIds = array();
        foreach ($pre_list as $item){
            $preparedIds[] = $item['id'];
        }

        $record_flags = Db::table('sheji.ques_flag_records')
            ->where('prepared_id', 'IN',$preparedIds)
            ->where('user_id', $userId)
            ->where('importance_flag', 'Y')
            ->select();

        $this->assign('record_flags',$record_flags);

        //-----------结束查询records importance flag


        $ques = Db::table('sheji.question_bank')
            ->where('id', $quesId)
            ->find();

        $type_list = Db::table('sheji.business_canvas_type')
            ->field('id,type_name')
            ->where('belong_to', $ques['tool_type'])
            ->order('display_order,id')
            ->select();

        $this->assign('ques_info',$ques);
        $this->assign('types',$type_list);



        if($ques['tool_type'] == '共感图'){
            if($ques['special_flag'] == 'targetUser') {
                $targetUser = '';
                if (sizeof($list) > 0) {
                    $targetUser = $list[0]['contents'];
                }
                $this->assign('targetUser', $targetUser);
            }else {
                $this->assign('targetUser', $ques['tool_extra']);
            }

            return $this->fetch('index/question_bank/gonggantu_ques');
        }else if($ques['tool_type'] == 'HMW'){

            $tmpInfo['extra'] = $ques['tool_extra'];
            $targetUser = $this->getToolExtraInfo($tmpInfo,'targetUser');
            $pain = $this->getToolExtraInfo($tmpInfo,'pain');
            $gain = $this->getToolExtraInfo($tmpInfo,'gain');

            $this->assign('targetUser',$targetUser);
            $this->assign('pain',$pain);
            $this->assign('gain',$gain);

            return $this->fetch('index/question_bank/HMW_ques');
        }else if($ques['tool_type'] == '用户体验地图') {
            $this->assign('column_num',[1,2,3,4]);
            return $this->fetch('index/question_bank/user_travel_map_ques');
        }



    }


    public function editQuesRecord($preId,$userId,$newRecord){
        $exist_record = Db::table('sheji.ques_records')
            ->where(['prepared_id'=>$preId,'author_id'=>$userId])
            ->find();

        if(sizeof($exist_record) > 0){
            Db::table('sheji.ques_records')
                ->where(['prepared_id'=>$preId,'author_id'=>$userId])
                ->update(['contents' => $newRecord]);

        }else{
            $preInfo = Db::table('sheji.ques_prepared_records')
                ->where('id',$preId)
                ->find();
            $typeId = $preInfo['type_id'];
            $quesId = $preInfo['ques_id'];


            Db::table('sheji.ques_records')
                ->data(['prepared_id'=>$preId,'author_id'=>$userId,'contents' => $newRecord,'type_id'=>$typeId,'ques_id'=>$quesId])
                ->insert();
        }

        Db::table('sheji.user_history')
            ->data(['user_id' => $userId, 'bh_type' => 'edit_ques', 'bh_time' => date('Y-m-d H:i:s', time()), 'record_id' => $preId])
            ->insert();


    }

    public function updateEmotionCurve($preIdArr, $userId,$newContents){
        $preIdArr = json_decode($preIdArr);
        $newContents = json_decode($newContents);
        foreach($preIdArr as $idx => $preId){
            $this->editQuesRecord($preId,$userId,$newContents[$idx][1]);
        }
    }


    /**获取该项目的工具
     *
     * @param $prjId
     * @return mixed 该项目的工具页面
     */
    public function getTools( $prjId)
    {
        if(! isset($_COOKIE['user'])) {
            return $this->fetch('homePage');
        }

        //判断该用户是否在该项目中（权限）
        $list_temp = Db::table('sheji.user_prj_links')
            ->field('id')
            ->where(['prj_id'=> $prjId, 'user_id' => $_COOKIE['user'], 'confirmed'=>'Y'])
            ->find();


        if(sizeof($list_temp) > 0) {//如果用户在该项目中

            $this->getQuesBank();//获取统一题库

            // 查询工具数据
            $list = Db::table('sheji.tools')
                ->field('id,tool_type,extra')
                ->where('prj_id', $prjId)
                ->where('ques_bank_id', '=',0)
                ->select();

            //向工具数据中添加extra info（共感图指目标用户，四象限指目标、x轴、y轴）
            for($i = 0; $i < sizeof($list);$i++) {
                if($list[$i]['tool_type'] == '共感图') {
                    $list[$i]['targetUser'] = $this->getToolExtraInfo($list[$i],"targetUser");
                }else if($list[$i]['tool_type'] == '四象限法') {
                    $list[$i]['purpose'] = $this->getToolExtraInfo($list[$i],"purpose");
                    //$list[$i]['xAxis'] = $this->getToolExtraInfo($list[$i],"xAxis");
                    //$list[$i]['yAxis'] = $this->getToolExtraInfo($list[$i],"yAxis");
                }
            }
            $this->assign("tools", $list);
            $this->assign("prjId", $prjId);


            //获取还未编辑过的tool
            $newToolIds = array();
            foreach ($list as $item){
                if($this->isToolNew($item['id'])){
                    $newToolIds[] = $item['id'];
                }
            }
            $this->assign("newToolIds",$newToolIds);



            //处理工具类型（“添加工具”功能）
            $toolTypes = array();
            foreach ($list as $item) {
                $toolTypes[] = $item['tool_type'];
            }
            //$this->assign("toolTypes", $toolTypes);
            $this->assign("allToolTypes", [ '商业模式画布','共感图','四象限法']);//固定所有的工具类型
            $onlyOneToolTypes = ['商业模式画布'];//固定 一个项目只能有一个的工具类型
            $this->assign("notBeAddedToolTypes",array_intersect($toolTypes, $onlyOneToolTypes));//交集：已经建立的和只能有一个的工具类型


            //获取项目信息和成员，并assign
            $this->getPrjInfo($prjId);
            $this->getPrjMembers($prjId);

            return $this->fetch('tools');
        }

    }

    /**获取项目名称和创始人并assign
     *
     * @param $prjId
     */
    public function getPrjInfo($prjId){
        $prjInfo = Db::table('sheji.projects')
            ->field('prj_name, creator_id')
            ->where('id', $prjId)
            ->find();

        $this->assign("prjInfo",$prjInfo);
    }

    /**获取项目成员id和用户名并assign
     * @param $prjId
     */
    public function getPrjMembers($prjId){
        $list = Db::table('sheji.user_prj_links')
            ->alias('t1')
            ->join('sheji.users t2','t1.user_id = t2.id')
            ->field('t2.id, usr_name')
            ->where('prj_id', $prjId)
            ->where('confirmed','Y')
            ->select();

        //dump($list);
        $this->assign("prjMembers",$list);

        return $list;
    }

    /**获取项目成员的邀请请求和被拒消息
     *
     * @return \stdClass
     */
    public function getPrjMemRequests(){
        if(isset($_COOKIE['user'])) {
            $request_list = Db::table('sheji.user_prj_links')
                ->alias('t1')
                ->join('sheji.projects t2', 't1.prj_id = t2.id')
                ->join('sheji.users u', 't1.invited_by = u.id')
                ->field('prj_name,t2.id,u.usr_name')
                ->where('user_id', $_COOKIE['user'])
                ->where('confirmed', 'N')
                ->select();


            $reject_list = Db::table('sheji.user_prj_links')
                ->alias('t1')
                ->join('sheji.projects t2', 't1.prj_id = t2.id')
                ->join('sheji.users u', 't1.user_id = u.id')
                ->field('prj_name,u.usr_name,t2.id')
                ->where('invited_by', $_COOKIE['user'])
                ->where('confirmed', 'R')
                ->select();

            $results = new \stdClass();
            $results -> request_list = $request_list;
            $results -> reject_list = $reject_list;

            return json($results);
        }
    }

    /**展示项目成员的邀请请求和被拒消息
     *
     * @return mixed 项目成员消息页面
     */
    public function showPrjMemRequests(){

        $results = $this->getPrjMemRequests();

        $this->assign('request_list', $results ->getData()->request_list);
        $this->assign('reject_list', $results ->getData()->reject_list);
        //$this->assign('request_list_len', sizeof($request_list));


        return $this->fetch('member_requests');
    }

    /**回应项目成员邀请请求
     *
     * @param $flag "Y"-同意加入；"R"-拒绝加入
     * @param $prjId
     * @return mixed 项目成员消息页面
     */
    public function joinPrjResponse($flag, $prjId){
        Db::table('sheji.user_prj_links')
            ->where(['prj_id'=> $prjId, 'user_id'=>$_COOKIE['user'], 'confirmed'=>'N'])
            ->update(['confirmed' => $flag]);


        if($flag == "Y"){
            $this->addUserHistory($_COOKIE['user'],'join',0,0,$prjId);
        }

        return $this->showPrjMemRequests();
    }

    /**回应用户拒绝加入项目消息
     *
     * @param $flag "DEL"-清除该消息
     * @param $prjId
     * @return mixed 项目成员消息页面
     */
    public function rejectJoiningPrjResponse($flag, $prjId){
        if($flag == "DEL") {
            Db::table('sheji.user_prj_links')
                ->where(['prj_id'=> $prjId, 'invited_by'=>$_COOKIE['user'], 'confirmed'=>'R'])
                ->delete();
        }

        return $this->showPrjMemRequests();
    }

    /**添加工具功能
     *
     */
    public function addTools(){
        $prjId = $_POST['prjId'];
        $toolType = $_POST['toolType'];
        $extra = "";


        //if($toolType == "共感图") {
        //    $extra = "targetUser-" . $_POST['targetUser'];
        //}else
        if($toolType == "四象限法"){
            //$extra = "purpose-".$_POST['purpose'].";type-".$_POST['sixiangxian_type'];
            $extra = "purpose-;type-".$_POST['sixiangxian_type'];
        }

        /*if($toolType == "商业模式画布"){//判断是否已经存在该项目的商业模式画布
            $judge_existance_list = Db::table('sheji.tools')
                ->field('id')
                ->where(['prj_id'=> $prjId,
                    'tool_type'=>$toolType])
                ->find();

            if(sizeof($judge_existance_list) == 0){
                Db::table('sheji.tools')
                    ->data(['prj_id' => $prjId, 'tool_type' => $toolType, 'extra'=> $extra])
                    ->insert();
            }*/
        //}else {//其他类型直接插入数据库
            Db::table('sheji.tools')
                ->data(['prj_id' => $prjId, 'tool_type' => $toolType, 'extra' => $extra])
                ->insert();
        //}

        /*
        if($toolType == "四象限法") {
            $getLastId = Db::name('sheji.tools')->getLastInsID();
            $data = [
                ['type_name' => "(-)" . $_POST['xAxis'] . " & (+)" . $_POST['yAxis'], 'belong_to' => "四象限法" . $getLastId],
                ['type_name' => "(+)" . $_POST['xAxis'] . " & (+)" . $_POST['yAxis'], 'belong_to' => "四象限法" . $getLastId],
                ['type_name' => "(-)" . $_POST['xAxis'] . " & (-)" . $_POST['yAxis'], 'belong_to' => "四象限法" . $getLastId],
                ['type_name' => "(+)" . $_POST['xAxis'] . " & (-)" . $_POST['yAxis'], 'belong_to' => "四象限法" . $getLastId]
            ];

            Db::name('sheji.business_canvas_type')->insertAll($data);
        }*/
    }

    public function getQuesTool($prjId, $quesId){
        $ques_info = Db::table('sheji.question_bank')
            ->where(['id' => $quesId])
            ->find();


        $tool_info = Db::table('sheji.tools')
            ->where(['prj_id' => $prjId, 'ques_bank_id' => $quesId])
            ->find();

        if(sizeof($tool_info) > 0){
            return $this->redirect('index/getRecords',['toolId' => $tool_info['id'], 'flag'=>"ques"]);
            //return $this->getRecords($tool_info['id']);
        }else{
            //新建该问题下的工具


            //附加信息
            if($ques_info['tool_type'] == '共感图'){
                $extra = 'targetUser-'.$ques_info['tool_extra'];

            }else if($ques_info['tool_type'] == 'HMW'){
                $extra = 'gain-'.$ques_info['content'];
            }

            Db::table('sheji.tools')
                ->data(['extra'=> $extra,'prj_id' => $prjId, 'tool_type'=>$ques_info['tool_type'], 'ques_bank_id' => $quesId])
                ->insert();

            $newId = Db::name('sheji.tools')->getLastInsID();

            //return $this->getRecords($newId);
            return $this->redirect('index/getRecords',['toolId' => $newId, 'flag'=>"ques"]);

        }
    }



    /**获取各种画布的条目内容及用户名等、工具基本信息、额外信息等
     *
     * @param $toolId
     * @return mixed 相应画布页面
     */
    public function getRecords($toolId, $flag = "")
    {
        if($flag == "ques"){
            $ques_info = Db::table('sheji.tools t')
                ->leftJoin('sheji.question_bank qb','t.ques_bank_id = qb.id')
                ->field('content,ques_type,extra')
                ->where(['t.id' => $toolId])
                ->find();
            $this->assign('ques_info',$ques_info);


        }


        //获取工具信息：工具类型和属于哪个项目
        $tool_info = Db::table('sheji.tools')
            ->alias('t')
            ->join('sheji.projects p','p.id = t.prj_id')
            ->field('prj_name,prj_id,tool_type,is_public,creator_id,ready_user_ids')
            ->where(['t.id' => $toolId])
            ->find();
        $type = $tool_info['tool_type'];
        $this->assign('prjInfo',$tool_info);

        //获取项目的成员数目
        $this->assign('memberSize',sizeof($this->getPrjMembers($tool_info['prj_id'])));

        if(! isset($_COOKIE['user'])){
            return $this->fetch('homePage');
        }

        $this->assign("toolId", $toolId);


        //-----------如果是用户旅程图进入另一个函数
        if($type == "用户旅程图"){

            return $this->getMapRecords($toolId);
        }


        //获取该用户有权限的条目
        $editable_list = Db::table('sheji.business_canvas')
            ->alias('t1')
            ->leftJoin('sheji.business_canvas_type t2', 't1.type_id = t2.id')
            ->field('t1.id')
            ->where(['tool_id' => $toolId,
                    'author_id' => $_COOKIE['user'],
                    'deleted' => 'N'])
            ->select();

        $editable_arr = array();
        foreach ($editable_list as $item){
            $editable_arr[] = $item['id'];
        }

        //获取该工具的所有条目
        $list = Db::table('sheji.business_canvas')
            ->alias('t1')
            ->leftJoin('sheji.business_canvas_type t2', 't1.type_id = t2.id')
            ->leftJoin('sheji.users u','t1.author_id = u.id')
            ->field('t1.id,type_id,type_name,contents,usr_name,color,favor,dislike,favor_count,dislike_count,adopt,adopt_count')
            ->where(['tool_id'=> $toolId,
                     'deleted' => 'N'])
            ->select();


        //用户名太长则取前10个字符，使用iconv系列函数（utf8一个汉字占3个字节，gb2312一个汉字占2个字节）
        for($i = 0; $i < sizeof($list); $i ++){
            if(iconv_strlen($list[$i]['usr_name']) > 10) {
                $list[$i]['usr_name'] = iconv_substr($list[$i]['usr_name'], 0, 10)."...";
            }


            $list[$i]['like'] = $list[$i]['favor'];
            $list[$i]['like_count'] = $list[$i]['favor_count'];


            //计算点赞点踩结果的相对颜色
            $list[$i]['like_relative_color'] = $this->getLikeRelativeColor($list[$i]['like_count'], $list[$i]['dislike_count'], 5);
        }


        //查询相应工具中的条目类型（以便前台打印模块）
        if($type == "四象限法") {
            //$belong_to = $type.$toolId;
            $sixiangxian_type = $this->getToolExtraInfo($this->getToolInfo($toolId), "type");
            $belong_to = $type.":".$sixiangxian_type;
            $type_list = Db::table('sheji.business_canvas_type')
                ->field('id,type_name')
                ->where('belong_to', $belong_to)
                ->order('display_order,id')
                ->select();
        }else{
            $type_list = Db::table('sheji.business_canvas_type')
                ->field('id,type_name')
                ->where('belong_to', $type)
                ->order('display_order,id')
                ->select();
        }

        $this->assign("records", $list);
        $this->assign("edit_records", $editable_arr);
        $this->assign("types", $type_list);



        //获取回收站里的内容
        //$this->getDeletedRecords($toolId);

        if($type == '商业模式画布') {
            return $this->fetch('business_canvas');
        }else if($type == '共感图'){
            //获取target user
            $targetUser = $this->getToolExtraInfo($this->getToolInfo($toolId), "targetUser");

            $this->assign("targetUser",$targetUser);

            if(strlen($targetUser) == 0 ){
                return $this->fetch('gonggantu_user');
            }else {
                return $this->fetch('gonggantu');
            }
        }else if($type == '四象限法'){
            //获取purpose
            $purpose = $this->getToolExtraInfo($this->getToolInfo($toolId), "purpose");
            $sixiangxian_type = $this->getToolExtraInfo($this->getToolInfo($toolId), "type");
            //$xAxis = $this->getToolExtraInfo($this->getToolInfo($toolId), "xAxis");
            //$yAxis = $this->getToolExtraInfo($this->getToolInfo($toolId), "yAxis");

            $this->assign("purpose",$purpose);
            $this->assign("sixiangxian_type",$sixiangxian_type);
            //$this->assign("xAxis",$xAxis);
            //$this->assign("yAxis",$yAxis);

            return $this->fetch('sixiangxian');
        }else if($type == 'HMW'){
            $targetUser = $this->getToolExtraInfo($this->getToolInfo($toolId), "targetUser");
            $gain = $this->getToolExtraInfo($this->getToolInfo($toolId), "gain");
            $pain = $this->getToolExtraInfo($this->getToolInfo($toolId), "pain");

            $this->assign("targetUser",$targetUser);
            $this->assign("gain",$gain);
            $this->assign("pain",$pain);

            return $this->fetch('HMW');
        }
    }



    public function getMapRecords($toolId){
        $list_nodes = Db::table('sheji.map_nodes')
            ->where(['tool_id'=> $toolId,
                'deleted' => 'N'])
            ->select();

        $list_links = Db::table('sheji.map_links')
            //->alias('t1')
            //->leftJoin('sheji.map_nodes t2', 't1.type_id = t2.id')
            ->where(['tool_id'=> $toolId,
                'deleted' => 'N'])
            ->select();


        $this->assign('nodes',$list_nodes);
        $this->assign('links',$list_links);


        return $this->fetch('user_travel_map');
    }

    public function addMapNode($toolId){
        Db::table('sheji.map_nodes')
            ->data(['tool_id'=>$toolId,'deleted'=>'N'])
            ->insert();

        $newRecordId = Db::name('sheji.map_nodes')->getLastInsID();

        return $newRecordId;
    }

    public function addMapLink($toolId,$srcId,$tarId){
        $list_links = Db::table('sheji.map_links')
            ->where(['src_id'=>$srcId,'tar_id'=>$tarId])
            ->find();

        if(sizeof($list_links) > 0){
            Db::table('sheji.map_links')
                ->where(['src_id'=>$srcId,'tar_id'=>$tarId])
                ->update(['deleted' => 'N']);
        }else {
            Db::table('sheji.map_links')
                ->data(['tool_id' => $toolId, 'src_id' => $srcId, 'tar_id' => $tarId, 'deleted' => 'N'])
                ->insert();
        }
        //$newRecordId = Db::name('sheji.map_links')->getLastInsID();

        //return $newRecordId;
    }

    public function editMapRecord($recordId,$contents){
        Db::table('sheji.map_nodes')
            ->where('id', $recordId)
            ->update(['contents' => $contents]);
    }

    public function editMapCoordinates($resultArr){
        foreach ($resultArr as $re) {
            $id = $re['id'];
            $idx_left = $re['left'];
            $idx_top = $re['top'];

            Db::table('sheji.map_nodes')
                ->where('id', $id)
                ->update(['idx_left' => $idx_left, 'idx_top' => $idx_top]);
        }
    }

    public function delMapLink($srcId, $tarId){
        Db::table('sheji.map_links')
            ->where('src_id', $srcId)
            ->where('tar_id', $tarId)
            ->update(['deleted' => 'Y']);

    }

    public function delMapNode($nodeId){
        Db::table('sheji.map_nodes')
            ->where('id', $nodeId)
            ->update(['deleted' => 'Y']);

        Db::table('sheji.map_links')
            ->where('src_id', $nodeId)
            ->whereOr('tar_id', $nodeId)
            ->update(['deleted' => 'Y']);
    }

    /**
    获取点赞点踩的结果 所对应的 相对颜色
     */
    public function getLikeRelativeColor($likeCount, $dislikeCount, $threshold){
        if($likeCount == 0 && $dislikeCount == 0){
            return "lightgray";
        }

        $diff = $likeCount - $dislikeCount;
        if($diff == 0){
            return "rgb(255,255,0)";
        }else if($diff > 0){
            if($diff >= $threshold ){
                $relativeNum = 0;
            }else {
                $relativeNum = 255 - $diff / $threshold * 255;
            }

            return "rgb(255,".$relativeNum.",0)";
        }else if($diff < 0){
            if($diff <= -$threshold ){
                $relativeNum = 0;
            }else {
                $relativeNum = 255 - (- $diff / $threshold * 255);
            }

            return "rgb(".$relativeNum.",255,0)";
        }
    }


    public function getDeletedRecords($toolId){
        $del_list = Db::table('sheji.business_canvas')
            ->alias('t1')
            ->leftJoin('sheji.business_canvas_type t2', 't1.type_id = t2.id')
            ->field('t1.id,type_id,contents,t2.type_name')
            ->where(['tool_id' => $toolId,
                'author_id' => $_COOKIE['user'],
                'deleted' => 'Y'])
            ->select();


        return json($del_list);
        //$this->assign("del_list",$del_list);

    }


    /**更改四象限图的目标
     * @param $toolId
     * @param $newPurpose
     * @return mixed 画布页面
     */
    public function changeSixiangxianPurpose($toolId,$newPurpose){

        $type = $this->getToolExtraInfo($this->getToolInfo($toolId),'type');

        $newExtra = "purpose-".$newPurpose.";type-".$type;
        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['extra' => $newExtra]);

        return $this->getRecords($toolId);

    }


    public function changeSixiangxianType($toolId, $type){

        $purpose = $this->getToolExtraInfo($this->getToolInfo($toolId),'purpose');


        $newExtra = "purpose-".$purpose.";type-".$type;
        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['extra' => $newExtra]);

        return $this->getRecords($toolId);

    }

    /**更改共感图的目标用户
     * @param $toolId
     * @param $newTargetUser
     * @return mixed 画布页面
     */
    public function changeGonggantuUser($toolId, $newTargetUser){
        $newExtra = "targetUser-".$newTargetUser;

        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['extra' => $newExtra]);

        return $this->getRecords($toolId);

    }


    public function changeGonggantuUser_ques($quesId, $authorId, $newTargetUser)
    {
        $list = Db::table('sheji.ques_records')
            ->where(['ques_id' => $quesId, 'author_id' => $authorId])
            ->find();

        if (sizeof($list) > 0) {
            Db::table('sheji.ques_records')
                ->where(['ques_id' => $quesId, 'author_id' => $authorId])
                ->update(['contents' => $newTargetUser]);
        }else{
            Db::table('sheji.ques_records')
                ->data(['ques_id' => $quesId, 'author_id' => $authorId, 'contents' => $newTargetUser])
                ->insert();
        }

        // return $this->getRecords($toolId);
    }


    public function changeHMWUser($toolId, $newTargetUser){
        $gain = $this->getToolExtraInfo($this->getToolInfo($toolId),'gain');
        $pain = $this->getToolExtraInfo($this->getToolInfo($toolId),'pain');


        $newExtra = "targetUser-".$newTargetUser.";gain-".$gain.";pain-".$pain;


        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['extra' => $newExtra]);

        return $this->getRecords($toolId);

    }

    public function changeHMWGain($toolId, $newGain){
        $targetUser = $this->getToolExtraInfo($this->getToolInfo($toolId),'targetUser');
        $pain = $this->getToolExtraInfo($this->getToolInfo($toolId),'pain');


        $newExtra = "targetUser-".$targetUser.";gain-".$newGain.";pain-".$pain;


        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['extra' => $newExtra]);

        return $this->getRecords($toolId);

    }

    public function changeHMWPain($toolId, $newPain){
        $gain = $this->getToolExtraInfo($this->getToolInfo($toolId),'gain');
        $targetUser = $this->getToolExtraInfo($this->getToolInfo($toolId),'targetUser');


        $newExtra = "targetUser-".$targetUser.";gain-".$gain.";pain-".$newPain;


        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['extra' => $newExtra]);

        return $this->getRecords($toolId);

    }

    /**获取工具的额外信息
     * @param $toolInfo
     * @param $infoType 信息类型，各种画布有所不同
     * @return mixed
     */
    public function getToolExtraInfo($toolInfo, $infoType){
        $extraInfo = "";
        if(strlen($toolInfo['extra']) > 0) {
            $toolInfoArr = explode(';', $toolInfo['extra']);

           foreach ($toolInfoArr as $item) {
                if (strstr($item, $infoType) == $item) {
                    $extraInfo = explode('-', $item)[1];
                }
            }
        }

        return $extraInfo;
    }

    /**获取工具基本信息
     * @param $toolId
     * @return array|mixed|null|\PDOStatement|string|\think\Model 即$toolInfo
     */
    public function getToolInfo($toolId){
        $toolInfo = Db::table('sheji.tools')
            ->field('prj_id, tool_type, extra')
            ->where('id', $toolId)
            ->find();

        return $toolInfo;
        //$this->assign("toolInfo",$toolInfo);
    }

    /**编辑条目
     *
     */
    public function editRecord(){

        $id = $_POST['id'];
        $newRecord = $_POST['newRecord'];
        Db::table('sheji.business_canvas')
            ->where('id', $id)
            ->update(['contents' => $newRecord]);

        $this->addUserHistory($_COOKIE['user'],'edit',$id,0,0);

    }

    /**添加条目到各类画布
     * @param $toolId
     * @param $recordTypeId
     * @param string $content
     * @param $userId
     */
    public function addRecordToBC($toolId, $recordTypeId, $content="",$userId){
        if($userId == ""){
            $userId = $_COOKIE['user'];
        }


        Db::table('sheji.business_canvas')
            ->data(['tool_id'=>$toolId, 'type_id'=>$recordTypeId, 'author_id'=>$userId, 'contents'=>$content,'adopt'=>$userId, 'adopt_count'=>1])
            ->insert();

        $newRecordId = Db::name('sheji.business_canvas')->getLastInsID();
        $this->addUserHistory($userId,'create',$newRecordId,0,0);



        $newRecord = Db::table('sheji.business_canvas')
            ->where('id', $newRecordId)
            ->find();
        //$this->assign("r",$newRecord);


        $result = new \stdClass();
        $result->recordId = $newRecordId;
        $result->typeId = $recordTypeId;

        $result->newRecord = $newRecord;
        return json($result);
        //刷新（-> 前台刷新）
        //$this->getRecords($toolId,"商业模式画布");
        //$this->fetch('business_canvas');
    }

    /**从各类画布删除条目
     * @param $id
     * @param $toolId
     */
    public function delRecordFromBC($id ){
        $list = Db::table('sheji.business_canvas')
           ->field('contents')
            ->where('id', $id)
            ->find();

        //print_r($list);
        if($list['contents'] == "") {
            Db::table('sheji.business_canvas')
                ->where('id',$id)
                ->delete();
        }else {

            Db::table('sheji.business_canvas')
                ->where('id', $id)
                ->update(['deleted' => 'Y']);
        }


        $this->addUserHistory($_COOKIE['user'],'del',$id,0,0);
        //$this->getRecords($toolId,"商业模式画布");
        //return $this->fetch('business_canvas');

    }

    public function revertRecord($id ){
        Db::table('sheji.business_canvas')
            ->where('id', $id)
            ->update(['deleted' => 'N']);


        $this->addUserHistory($_COOKIE['user'],'recycle',$id,0,0);


        $revertedRecord = Db::table('sheji.business_canvas')
            ->where('id', $id)
            ->find();
        //$this->assign("r",$newRecord);


        return json($revertedRecord);
        //$this->getRecords($toolId,"商业模式画布");
        //return $this->fetch('business_canvas');

    }


    public function likeOrDislikeRecord($recordId, $userId, $like_or_dislike){
        if($like_or_dislike == "like"){
            $like_or_dislike = "favor";
        }

        if($like_or_dislike == "favor")
            $contrary = "dislike";
        else
            $contrary = "favor";


        $field_tmp = $like_or_dislike. ",". $like_or_dislike."_count,".$contrary;
        $list = Db::table('sheji.business_canvas')
           ->field($field_tmp)
            ->where('id', $recordId)
            ->find();




        //判断该用户之前是否已经点赞或点踩
        if(! in_array($userId, explode(',',$list[$like_or_dislike])) && ! in_array($userId, explode(',',$list[$contrary]))) {

            if (strlen($list[$like_or_dislike]) == 0) {
                $new_record = $userId;
            } else {
                $new_record = $list[$like_or_dislike] . "," . $userId;
            }

            $new_count = $list[$like_or_dislike."_count"] + 1;


            $field_tmp = $like_or_dislike."_count";
            Db::table('sheji.business_canvas')
                ->where('id', $recordId)
                ->update([$like_or_dislike => $new_record,
                     $field_tmp => $new_count]);

            $this->addUserHistory($userId,$like_or_dislike,$recordId,0,0);
        }
    }


    public function cancelLikeOrDislikeRecord($recordId, $userId, $like_or_dislike){

        if($like_or_dislike == "like"){
            $like_or_dislike = "favor";
        }


        $field_tmp = $like_or_dislike. ",". $like_or_dislike."_count";
        $list = Db::table('sheji.business_canvas')
            ->field($field_tmp)
            ->where('id', $recordId)
            ->find();


        //判断该用户之前是否已经点赞或点踩
        if(strlen($list[$like_or_dislike]) > 0 && in_array($userId, explode(',',$list[$like_or_dislike]))) {

            $arr_tmp = explode(',',$list[$like_or_dislike]);


            array_splice($arr_tmp,array_search($userId ,$arr_tmp),1);

            $new_record = implode(',',$arr_tmp);


            $new_count = $list[$like_or_dislike."_count"] - 1;


            $field_tmp = $like_or_dislike."_count";
            Db::table('sheji.business_canvas')
                ->where('id', $recordId)
                ->update([$like_or_dislike => $new_record,
                    $field_tmp => $new_count]);

            $this->addUserHistory($userId,"cancel_".$like_or_dislike,$recordId,0,0);
        }
    }


    public function passRecord($recordId, $userId){

        $list = Db::table('sheji.business_canvas')
            ->field('adopt,adopt_count')
            ->where('id', $recordId)
            ->find();


        //判断该用户之前是否已经通过
        if(! in_array($userId, explode(',',$list['adopt'])) ) {

            if (strlen($list['adopt']) == 0) {
                $new_record = $userId;
            } else {
                $new_record = $list['adopt'] . "," . $userId;
            }

            $new_count = $list['adopt_count'] + 1;

            Db::table('sheji.business_canvas')
                ->where('id', $recordId)
                ->update(['adopt' => $new_record,
                    'adopt_count' => $new_count]);


            $this->addUserHistory($userId,'pass',$recordId,0,0);
        }
    }


    public function cancelPassRecord($recordId, $userId){

     $list = Db::table('sheji.business_canvas')
            ->field('adopt,adopt_count')
            ->where('id', $recordId)
            ->find();


        //判断该用户之前是否已经点赞或点踩
        if(strlen($list['adopt']) > 0 && in_array($userId, explode(',',$list['adopt']))) {

            $arr_tmp = explode(',',$list['adopt']);
            array_splice($arr_tmp,array_search($userId ,$arr_tmp),1);

            $new_record = implode(',',$arr_tmp);

            $new_count = $list["adopt_count"] - 1;


            Db::table('sheji.business_canvas')
                ->where('id', $recordId)
                ->update(['adopt' => $new_record,
                    'adopt_count' => $new_count]);


            $this->addUserHistory($userId,'cancel_pass',$recordId,0,0);
        }
    }



    /**
     * 改变条目的颜色
     */
    public function changeRecordColor(){
        $recordId = $_POST['id'];
        $color = $_POST['color'];

        Db::table('sheji.business_canvas')
            ->where('id', $recordId)
            ->update(['color' => $color]);
    }


    public function getPublicCanvasLists(){
        if(isset($_COOKIE['user'])) {
            /*$public_tools = Db::table('sheji.tools')
                ->alias('t')
                ->join('sheji.projects p', 'p.id = t.prj_id')
                ->field('prj_name,prj_id,tool_type,t.id')
                ->where(['is_public' => 'Y'])
                ->select();


            for($i=0; $i < sizeof($public_tools); $i++){
                if($public_tools[$i]['tool_type'] == '四象限法'){
                    $public_tools[$i]['sixiangxian_type'] = $this->getToolExtraInfo($this->getToolInfo($public_tools[$i]['id']), 'type');
                }
            }*/

            $public_tools_pagi = Db::table('sheji.tools')
                ->alias('t')
                ->join('sheji.projects p', 'p.id = t.prj_id')
                ->field('prj_name,prj_id,tool_type,t.id')
                ->where(['is_public' => 'Y'])
                ->order('public_time','desc')
                ->paginate(10)
                ->each(function($item, $key){
                    //$item['sixiangxian_type'] = $this->getToolExtraInfo($this->getToolInfo($item['id']), 'type');
                    $item['targetUser'] = $this->getToolExtraInfo($this->getToolInfo($item['id']), 'targetUser');
                    $item['purpose'] = $this->getToolExtraInfo($this->getToolInfo($item['id']), 'purpose');

                    return $item;
                });



            $this->assign('public_tools_pagi', $public_tools_pagi);

            //获得“我的小组”标识
            $this->getProjects($_COOKIE['user']);

            return $this->fetch('public_cases_home');
        }else{
            return $this->fetch('homePage');
        }
    }

    public function getPublicRecords($toolId){
        if(! isset($_COOKIE['user'])){
            return $this->fetch('homePage');
        }


        //获取工具信息：工具类型和属于哪个项目
        $tool_info = Db::table('sheji.tools')
            ->alias('t')
            ->join('sheji.projects p','p.id = t.prj_id')
            ->field('prj_name,prj_id,tool_type,is_public')
            ->where(['t.id' => $toolId])
            ->find();

        if($tool_info['is_public'] == 'Y') {
            $type = $tool_info['tool_type'];
            $this->assign('prjInfo', $tool_info);


            //获取该工具的所有条目
            $list = Db::table('sheji.business_canvas')
                ->alias('t1')
                ->join('sheji.business_canvas_type t2', 't1.type_id = t2.id')
                ->join('sheji.users u', 't1.author_id = u.id')
                ->field('t1.id,type_name,contents,usr_name,color,favor,dislike,favor_count,dislike_count')
                ->where(['tool_id' => $toolId,
                    'deleted' => 'N'])
                ->select();


            //用户名太长则取前10个字符，使用iconv系列函数（utf8一个汉字占3个字节，gb2312一个汉字占2个字节）
            for ($i = 0; $i < sizeof($list); $i++) {
                if (iconv_strlen($list[$i]['usr_name']) > 10) {
                    $list[$i]['usr_name'] = iconv_substr($list[$i]['usr_name'], 0, 10) . "...";
                }


                $list[$i]['like'] = $list[$i]['favor'];
                $list[$i]['like_count'] = $list[$i]['favor_count'];


                //计算点赞点踩结果的相对颜色
                $list[$i]['like_relative_color'] = $this->getLikeRelativeColor($list[$i]['like_count'], $list[$i]['dislike_count'], 5);

            }


            //查询相应工具中的条目类型（以便前台打印模块）
            if ($type == "四象限法") {
                //$belong_to = $type.$toolId;
                $sixiangxian_type = $this->getToolExtraInfo($this->getToolInfo($toolId), "type");
                $belong_to = $type . ":" . $sixiangxian_type;
                $type_list = Db::table('sheji.business_canvas_type')
                    ->field('id,type_name')
                    ->where('belong_to', $belong_to)
                    ->order('display_order,id')
                    ->select();
            } else {
                $type_list = Db::table('sheji.business_canvas_type')
                    ->field('id,type_name')
                    ->where('belong_to', $type)
                    ->order('display_order,id')
                    ->select();
            }

            $this->assign("records", $list);
            $this->assign("types", $type_list);
            $this->assign("toolId", $toolId);


            if($type == '商业模式画布') {
                //return $this->fetch('business_canvas');
            }else if($type == '共感图'){
                //获取target user
                $targetUser = $this->getToolExtraInfo($this->getToolInfo($toolId), "targetUser");

                $this->assign("targetUser",$targetUser);
                return $this->fetch('gonggantu_public');
            }else if($type == '四象限法'){
                //获取purpose
                $purpose = $this->getToolExtraInfo($this->getToolInfo($toolId), "purpose");
                $sixiangxian_type = $this->getToolExtraInfo($this->getToolInfo($toolId), "type");
                //$xAxis = $this->getToolExtraInfo($this->getToolInfo($toolId), "xAxis");
                //$yAxis = $this->getToolExtraInfo($this->getToolInfo($toolId), "yAxis");

                $this->assign("purpose",$purpose);
                $this->assign("sixiangxian_type",$sixiangxian_type);
                //$this->assign("xAxis",$xAxis);
                //$this->assign("yAxis",$yAxis);

                return $this->fetch('sixiangxian_public');
            }


        }
    }


    public function makeCanvasPublic($toolId){
        //判断当前用户是否在该工具所属项目中
        $list = Db::table('sheji.user_prj_links a')
            ->join('sheji.tools t','a.prj_id = t.prj_id')
            ->field('a.id')
            ->where(['t.id'=> $toolId, 'user_id' => $_COOKIE['user'], 'confirmed'=>'Y'])
            ->find();


        if(sizeof($list) != 0) {

            Db::table('sheji.tools')
                ->where('id', $toolId)
                ->update(['is_public' => 'Y', 'public_time' => date('Y-m-d H:i:s', time())]);

            return $this->getRecords($toolId);
        }
    }


    public function makeCanvasPrivate($toolId){
        //判断当前用户是否在该工具所属项目中
        $list = Db::table('sheji.user_prj_links a')
            ->join('sheji.tools t','a.prj_id = t.prj_id')
            ->field('a.id')
            ->where(['t.id'=> $toolId, 'user_id' => $_COOKIE['user'], 'confirmed'=>'Y'])
            ->find();


        if(sizeof($list) != 0) {

            Db::table('sheji.tools')
                ->where('id', $toolId)
                ->update(['is_public' => 'N']);

            return $this->getRecords($toolId);
        }
    }

    public function changeRecordType($recordId, $newTypeId){
        Db::table('sheji.business_canvas')
            ->where('id', $recordId)
            ->update(['type_id' => $newTypeId]);


        $this->addUserHistory($_COOKIE['user'],'move',$recordId,0,0);
    }



    public function getDesignMethods(){
        return $this->fetch('designMethods');
    }

    /**画布导出为txt
     *
     */
    public function exportRecords(){
        $toolId = $_POST['toolId'];

        /* 项目名：工具类型
           [extra info]
           \r\n
           -----------记录类型1----------
           用户名：内容
           用户名：内容
         * */

        $prjName = Db::table('sheji.tools')
            ->alias('t1')
            ->join('sheji.projects t2','t1.prj_id = t2.id')
            ->field('tool_type,prj_name,extra')
            ->where('t1.id',  $toolId)
            ->find();

        //dump($prjName);

        $contents = Db::table('sheji.business_canvas')
            ->alias('t1')
            ->join('sheji.business_canvas_type t2','t1.type_id = t2.id')
            ->join('sheji.users u','t1.author_id = u.id')
            ->field('type_name,usr_name,contents')
            ->where(['tool_id' =>  $toolId,
                    'deleted' => 'N'])
            ->order(['type_id','author_id'])
            ->select();


        file_put_contents("../public/files/".$toolId."_export.txt",$prjName['prj_name']."：".$prjName['tool_type']."\r\n");
        file_put_contents("../public/files/".$toolId."_export.txt",$prjName['extra'], FILE_APPEND);


        file_put_contents("../public/files/".$toolId."_export.txt","\r\n", FILE_APPEND);


        for($idx = 0; $idx < sizeof($contents); $idx++){
            if($idx == 0 || $contents[$idx]['type_name'] != $contents[$idx - 1]['type_name']){
                file_put_contents("../public/files/" . $toolId . "_export.txt", "-----------" . $contents[$idx]['type_name'] . "----------\r\n", FILE_APPEND);
            }
            file_put_contents("../public/files/".$toolId."_export.txt",$contents[$idx]['usr_name']."：".$contents[$idx]['contents']."\r\n", FILE_APPEND);
        }

        //file_put_contents("../public/files/".$toolId."_export.txt",json_encode($contents), FILE_APPEND);
        //dump($contents);

        return $this->download($toolId);
    }

    /**下载txt文件
     * @param $toolId
     * @return \think\response\Download
     */
    public function download($toolId)
    {
        return download("../public/files/".$toolId."_export.txt", 'mycanvas.txt');
    }

    /**添加反馈
     * @param $feedbackInfo
     */
    public function addFeedback($feedbackInfo,$userId){
        /*if(isset($_COOKIE['user'])){
            $userId = $_COOKIE['user'];
        }else{
            $userId = "-1";
        }*/


        Db::table('sheji.feedback')
            ->data(['usr_id'=>$userId,'content'=>$feedbackInfo, 'date'=>date('Y-m-d H:i:s',time())])
            ->insert();
    }


    public function addUserHistory($userId, $bh_type,$recordId=0,$toolId=0,$prjId=0){
        if($_COOKIE['user'] == $userId) {
            if(is_array($recordId)){
                foreach ($recordId as $id){
                    Db::table('sheji.user_history')
                        ->data(['user_id' => $userId, 'bh_type' => $bh_type, 'bh_time' => date('Y-m-d H:i:s', time()), 'record_id' => $id, 'tool_id' => $toolId, 'prj_id' => $prjId])
                        ->insert();
                }
            }else {

                Db::table('sheji.user_history')
                    ->data(['user_id' => $userId, 'bh_type' => $bh_type, 'bh_time' => date('Y-m-d H:i:s', time()), 'record_id' => $recordId, 'tool_id' => $toolId, 'prj_id' => $prjId])
                    ->insert();
            }
        }
    }


    public function updateToolReady($userId, $toolId){
        $list = Db::table('sheji.tools')
            ->field('ready_user_ids')
            ->where('id',  $toolId)
            ->find();

        $oldUserIds = $list['ready_user_ids'];

        $newUserIds = $userId;
        if(strlen($oldUserIds) > 0){
            $newUserIds = $oldUserIds.",".$userId;
        }


        Db::table('sheji.tools')
            ->where('id', $toolId)
            ->update(['ready_user_ids' => $newUserIds]);
    }

    public function cancelToolReady($userId, $toolId)
    {
        $list = Db::table('sheji.tools')
            ->field('ready_user_ids')
            ->where('id', $toolId)
            ->find();

        $oldUserIds = $list['ready_user_ids'];

        if (strlen($oldUserIds) > 0 && in_array($userId, explode(',', $oldUserIds))) {
            $arr_tmp = explode(',', $oldUserIds);
            array_splice($arr_tmp, array_search($userId, $arr_tmp), 1);

            $newUserIds = implode(',', $arr_tmp);


            Db::table('sheji.tools')
                ->where('id', $toolId)
                ->update(['ready_user_ids' => $newUserIds]);
        }
    }



    public function isToolNew($toolId){
        $list = Db::table('sheji.business_canvas')
            ->field('id')
            ->where('tool_id', $toolId)
            ->find();

        if(sizeof($list) == 0){
            return true;
        }else{
            return false;
        }

    }


    public function addRecordComment($recordId,$userId,$contents){
        Db::table('sheji.comments')
            ->data(['user_id' => $userId, 'record_id' => $recordId,'contents'=>$contents, 'time' => date('Y-m-d H:i:s', time()),  'deleted' => 'N'])
            ->insert();
    }

    public function getRecordComments($recordId){
        $list = Db::table('sheji.comments')
            ->alias('c')
            ->join('sheji.users u','c.user_id = u.id')
            ->field('c.id,user_id,contents,usr_name,time')
            ->where(['record_id' =>  $recordId,
                'deleted' => 'N'])
            //->order(['type_id','author_id'])
            ->select();

        return json($list);
    }

    public function delRecordCmt($cmtId){
        $list = Db::table('sheji.comments')
            ->field('user_id')
            ->where('id', $cmtId)
            ->find();


        if($_COOKIE['user'] == $list['user_id']) {
            Db::table('sheji.comments')
                ->where('id', $cmtId)
                ->update(['deleted' => 'Y']);
        }
    }

    public function getTravelMap(){
        return $this->fetch('user_travel_map');
    }
}
